package com.moonshineproject.plugin.actionscript.flashproject
{
	import com.moonshineproject.IDEModel;
	import com.moonshineproject.events.FilePluginEvent;
	import com.moonshineproject.plugin.PluginBase;
	import com.moonshineproject.plugin.core.compiler.CompilerEventBase;
	import com.moonshineproject.plugin.project.event.ProjectEvent;
	import com.moonshineproject.plugin.project.vo.ProjectVO;
	import com.moonshineproject.utils.Utils;
	
	import flash.events.Event;
	import flash.filesystem.File;
	
	public class FlashProjectPlugin extends PluginBase
	{
		override public function get name():String 			{return "Flash Project Plugin";}
		override public function get author():String 		{return "Moonshine Project Team";}
		override public function get description():String 	{return "Flash project compiling.";}
		
		private var flashIDE:MacFlashIDELaunchCommand = new MacFlashIDELaunchCommand;
		
		override public function activate():void
		{
			dispatcher.addEventListener(FilePluginEvent.EVENT_FILE_OPEN, handleFileOpen);
			
			dispatcher.addEventListener(CompilerEventBase.BUILD_AND_RUN, handleBuild);
			registerCommand('run', buildCommand);
			
		}
		
		override public function deactivate():void
		{
			dispatcher.addEventListener(FilePluginEvent.EVENT_FILE_OPEN, handleFileOpen);
	
			dispatcher.removeEventListener(CompilerEventBase.BUILD_AND_RUN, handleBuild);		
			unregisterCommand('run');
		}
				
				
		private function handleFileOpen(event:FilePluginEvent):void
		{
			if (event.file.extension == 'fla')
			{
				// Is file in an already opened project?
				for each (var p:ProjectVO in model.projects)
				{
					if ( event.file.nativePath.indexOf(p.folder.nativePath) == 0 )
					{
						return;
					}
				}
				
				event.preventDefault();
				
				var rootPath:String = Utils.getDirectoryPathFor(event.file);
				var root:File = new File(rootPath);
				openProject(root, event.file);
			}
			else if (event.file.extension == 'flx')
			{
				
			}
		}
		
		private function openProject(root:File, main:File):void
		{
			var p:FlashProjectVO = new FlashProjectVO(root);
			p.projectFile = main;
			
			// Don't open a project twice
			for each (var pr:ProjectVO in model.projects)
			{
				if (pr.folder.nativePath == p.folder.nativePath)
				{
					model.activeProject = pr;
					warning("Project already opened. Ignoring.");
					return;
				}
			}
			
			dispatcher.dispatchEvent(
				new ProjectEvent(ProjectEvent.ADD_PROJECT, p)
			);
		}
		
		private function buildCommand(args:Array):void
		{
			build();
		}
		
		private function handleBuild(event:Event):void
		{
			build();
		}
		
		private function build():void
		{
			var pvo:FlashProjectVO = IDEModel.getInstance().activeProject as FlashProjectVO;
			
			if (!pvo) return;
			
			// Let the Flash IDE do it's thing
			flashIDE.buildFla(pvo.projectFile);
		}
		
	}
}